package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xrit.sunnyday.dao.PermissionMapper;
import com.xrit.sunnyday.pojo.Permission;
import com.xrit.sunnyday.service.PermissionService;
import com.xrit.sunnyday.common.MessageConstant;
import com.xrit.sunnyday.common.PageResult;
import com.xrit.sunnyday.common.QueryPageBean;
import com.xrit.sunnyday.common.SunnydayException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //判断是否有条件
        if(!(StringUtils.isEmpty(queryPageBean.getQueryString()))){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        //开启分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //调用查询方法
        List<Permission> permissionList = permissionMapper.findPage(queryPageBean.getQueryString());
        //放入pageinfo中
        PageInfo<Permission> pageInfo = new PageInfo<>(permissionList);
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public void add(Permission permission) {
        permissionMapper.add(permission);
    }

    @Override
    public void deleteById(Integer id) throws SunnydayException {
        //调用根据id查询角色权限中间表的方法
        int count = permissionMapper.findPermissionRoleById(id);
        //判断该权限是否和角色有关系
        if(count>0){
            //抛出异常
            throw new SunnydayException(MessageConstant.DELETE_PERMISSION_ERROR);
        }
        //删除权限
        permissionMapper.deleteById(id);
    }

    @Override
    public Permission findById(Integer id) {
        return permissionMapper.findById(id);
    }

    @Override
    public void update(Permission permission) {
        permissionMapper.update(permission);
    }
}
